<?php

namespace Core\Http\Client;

use Psr\Http\Message\ResponseInterface;

class HttpResponse
{
    public const HTTP_OK = 200;

    protected $headers;
    protected $code;
    protected $contents;

    public function __construct(ResponseInterface $response)
    {
        $this->headers = $response->getHeaders();
        $this->code = $response->getStatusCode();

        // get contents
        $body = $response->getBody();
        $this->contents = $body->getContents();
    }

    public function getHeaders()
    {
        return $this->headers;
    }

    public function getContents()
    {
        return $this->contents;
    }

    public function getStatusCode()
    {
        return $this->code;
    }

    /**
     * 检查响应状态码是否是200
     */
    public function ok()
    {
        return $this->getStatusCode() === self::HTTP_OK ? true : false;
    }

    /**
     * 获取json类型, 如果解码失败返回原始数据
     */
    public function getJson($associative = false)
    {
        $content = $this->getContents();
        $j = json_decode($content, $associative);

        if (is_null($j)) {
            return $content;
        }

        return $j;
    }
}
